package com.sakhalin.news.viewmodels.datasource

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.sakhalin.news.BuildConfig
import com.sakhalin.news.models.news.NewsItem
import com.sakhalin.news.repositories.NewsListRepository
import com.sakhalin.news.viewmodels.NO_DATA_ERROR_TEXT
import kotlinx.coroutines.delay

class NewsListDataSource(
    private val category: String,
    private val repository: NewsListRepository = NewsListRepository()
) : PagingSource<String, NewsItem>() {

    override fun getRefreshKey(state: PagingState<String, NewsItem>): String? {
        return null
    }

    override suspend fun load(params: LoadParams<String>): LoadResult<String, NewsItem> {
        if(BuildConfig.DEBUG) delay(1000)

        return try {
            val nextKey = params.key ?: ""

            val response = repository.getNewsListByCategory(category, nextKey)

            if (response.isError) {
                throw Exception(response.errorText)
            } else {

                val articles = checkNotNull(response.content)

                LoadResult.Page(
                    data = articles,
                    prevKey = if (nextKey.isEmpty()) null else response.date,
                    nextKey = response.nextDate
                )
            }

        } catch (e: Exception) {
            e.printStackTrace()
            LoadResult.Error(if (BuildConfig.DEBUG) e else Exception(NO_DATA_ERROR_TEXT))
        }
    }
}